function qs(ele) {
  return document.querySelector(ele)
}
axios.defaults.baseURL = 'http://ajax-api.itheima.net'



const nickname = qs('[name=nickname]')
const upload = qs('#upload')
const avatar = qs('.figure img')
const province = qs('[name=province]')
const city = qs('[name=city]')
const area = qs('[name=area]')
const figure=qs('.figure-caption')
const form = qs('form')

//封装渲染省的函数
async function getproviceData() {
  const {
      data: res
  } = await axios.get('/api/province')
  console.log(res);
  let shengStr = res.data.map(item => {
      return `<option value="${item}">${item}</option>`
  }).join('')
  console.log(shengStr);
  province.innerHTML = '<option value="">请选择省份</option>' + shengStr
}
// getproviceData()

//封装渲染市的函数
async function getCityData(pname) {
  const {
      data: res
  } = await axios.get('/api/city', {
      params: {
          pname,
      }
  })
  console.log(res);
  let shiStr = res.data.map(item => {
      return `<option value="${item}">${item}</option>`
  }).join('')
  
  city.innerHTML = '<option value="">请选择城市</option>' + shiStr
}

//封装渲染县的函数
async function getCountyData(pname,cname) {
  const {
      data: res
  } = await axios.get('/api/area', {
      params: {
          pname,
          cname,
      }
  })
  console.log(res);
  let quStr = res.data.map(item => {
      return `<option value="${item}">${item}</option>`
  }).join('')
  area.innerHTML = '<option value="">请选择区县</option>' + quStr
}

//页面初始化渲染
async function fn() {
  await getproviceData()
  province.value = '安徽省'
  await getCityData('安徽省')
  city.value = '合肥市'
  await getCountyData('安徽省','合肥市')
  area.value = '瑶海区'
}
fn()

//页面点击事件
province.addEventListener('change', async function () {
  // console.log(this.value);
  getCityData(this.value)
  area.innerHTML = '<option value="">请选择区县</option>'
})

city.addEventListener('change', async function () {
  console.log(this.value);
  getCountyData(province.value,this.value)
})



//头像上传
function touxiang(){
  avatar.addEventListener('click',function(){
    upload.click()
  })
  upload.addEventListener('change',async function(){
    const file = this.files[0]
    if (!file) { return }
    const fd = new FormData()
    fd.append('avatar',file)
    const {data:{data}} = await axios.post('/api/file',fd)
    // console.log( data)
    avatar.src =data.url
  })
}
touxiang() 


//保存资料按钮
async function getData(){
  const data ={
    nickname:nickname.value,
    province:province.value,
    city:city.value,
    area:area.value,
    avatar:avatar.src
  }
  const res = await axios.put('/api/settings',data)
}
form.addEventListener('submit',function(e){
  e.preventDefault()
  getData()
})
 //页面开始渲染函数
async function render() {
  const {data:{data}} = await axios.get('/api/settings')
  console.log(data)
  nickname.value =data.nickname
  // province.value=data.province
  // city.value=data.city
  // area.value=data.area
  avatar.src =data.avatar
  // sheng(data.province,data.city,data.area)
}
render()